import { createCom } from './dom'

let queryDomID = function (v) {
  return document.querySelector('[domId=\'' + v + '\']')
}

function createEl(node, tagType = 'div', cb) {
  console.log('createEl', node, tagType)
  var com = createCom(tagType, {
    // id: getDomId(node.id),
    ...node.attributes
  })
  if (node.props) {
    for (let propKey in node.props) {
      com.el[propKey] = node.props[propKey]
    }
  }
  if (node.cssText) {
    // console.log('node.cssText', node.cssText)
    com.el.style = node.cssText
  }
  cb && cb(com.el, com)
  return com
}

export function getDataset(id) {
  let domIDTpl = queryDomID(id)
  let dataset = {}
  if (domIDTpl) {
    dataset = domIDTpl.dataset
  }
  return dataset
}

class BaseCom {
  constructor(node) {
    this.node = node
  }
  getCom() {
    let node = this.node
    let dataset = node.dataset
    if (!dataset) {
      dataset = getDataset(node.domId)
    }
    var com = createEl(node, dataset.comType)
    com.dataset = dataset
    return com
  }
  getEl() {
    return this.getCom().el
  }
}

class ParentCom extends BaseCom {
  constructor(node) {
    super(node)
  }
  getEl() {
    return super.getEl()
  }
}

// var ele
// if (dataset.comType) {
//   ele = MoveTest.createEle(node, dataset.comType, function(ele, com) {
//     com.el.textContent = node.name
//   })
// }

class SubCom extends BaseCom {
  constructor(node) {
    super(node)
  }
  getEl() {
    let com = this.getCom()
    if (com.dataset) {
      if (com.dataset.initText) {
        com.el.textContent = com.dataset.initText
      }
    }
    return com.el
  }
}

let componentDefine = {
  ParentCom,
  SubCom
}

export let getComDef = function(name, ...args) {
  return  Reflect.construct(componentDefine[name], args);
}
